<template>
  <div>
    <el-form :inline="true" :model="page" class="demo-form-inline">
      <el-form-item label="耳号">
        <el-select v-model="page.basicInforId" placeholder="请选择" style="width:190px" clearable>
          <el-option v-for="item in BasicInformationList.filter((d:any)=>d.gender==2)" :label="item.earNumber" :value="item.basicInforId" />
        </el-select>
      </el-form-item>
      <el-form-item label="当前栋舍">
            <el-input v-model="page.turnBuilding" clearable />
        </el-form-item>
      <el-form-item label="窝号">
        <el-input v-model="page.nestNumber" placeholder="请输入窝号" clearable />
      </el-form-item>
      <el-form-item label="转入栋舍">
            <el-select v-model="page.bedroomId" placeholder="请选择" style="width:190px"  clearable>
                <el-option v-for="item in bedroomList" :label="item.bedroomName"
                :value="item.bedroomId" />
            </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="loadData">查询</el-button>
        <el-button type="danger" @click="Export">导出</el-button>
        <!--导入-->
        <el-button type="danger" @click="ImportFarrow">导入</el-button>
        <!--选择文件-->
        <input type="file" @change="handleFileUpload">
      </el-form-item>
    </el-form>
    <!-- 母猪分娩列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="farrowingId" label="序号" width="100" align="center" />
      <el-table-column prop="earNumber" label="耳号" width="100" align="center" />
      <el-table-column property="farrowingDate" label="分娩日期" width="130">
      <template #default="scope">
        {{ scope.row.farrowingDate.replace('T',' ').substr(0,10) }}
      </template>
    </el-table-column>
      <el-table-column prop="gestationNum" label="妊娠天数" width="100" align="center">
        <template #default="scope">
          {{ scope.row.gestationNum }}天
        </template>
      </el-table-column>
      <el-table-column prop="difficultieName" label="分娩难易" width="100" align="center" />
      <el-table-column prop="batchName" label="肥羊批次" width="100" align="center" />
      <el-table-column prop="maternalName" label="母性" width="100" align="center" />
      <el-table-column prop="lactation" label="泌乳" width="100" align="center" />
      <el-table-column prop="mastitis" label="乳房炎" width="100" align="center" />
      <el-table-column prop="nestNumber" label="窝号" width="100" align="center" />
      <el-table-column prop="livePigNum" label="活猪数" width="100" align="center">
        <template #default="scope">
          {{ scope.row.livePigNum }}只
        </template>
      </el-table-column>
      <el-table-column prop="nestWeight" label="窝总重(公斤)" width="100" align="center">
        <template #default="scope">
          {{ scope.row.nestWeight }}公斤
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" align="center" >
                <template #default="scope">
                <el-tag type="primary" v-if="scope.row.gender==1">公</el-tag>
                <el-tag type="danger" v-else>母</el-tag>
                </template>
      </el-table-column>
      <el-table-column prop="turnBuilding" label="转出栋舍" align="center" />
      <el-table-column prop="turnColumn" label="转出栏位" align="center" />
      <el-table-column prop="bedroomName" label="转入栋舍" align="center" />
      <el-table-column prop="fieldName" label="转入栏位" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" @click="Del(scope.row.farrowingId)" link>删除</el-button>
          <el-button type="primary" @click="Getfarrowing(scope.row.farrowingId)" link>查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <table>
      <tr>
        <td>
          <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
            :page-sizes="[5, 10, 15, 20]" :background="true" layout="total,slot, prev, pager,next" :total="page.totalCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
            ,每页显示{{ page.pageSize }},当前第{{ page.pageIndex }}/{{ page.pageCount }}
            <el-button class="btn-prev" @click="handleCurrentChange(1)">首页</el-button>
          </el-pagination>
        </td>
        <td>
          <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
            :page-sizes="[5, 10, 15, 20]" :background="true" layout="slot,sizes,jumper" :total="page.totalCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange">
            <el-button class="btn-prev" @click="handleCurrentChange(page.pageCount)">尾页</el-button>
          </el-pagination>
        </td>
      </tr>
    </table>

  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

const apiUrl = import.meta.env.VITE_APP_API_URL;
const apiBedinUrl = import.meta.env.VITE_APPRead_API_URL;

const router = useRouter();
onMounted(() => {
  loadData();
  GetBasicInformation();//猪只耳号
  handleBedroom();//栋舍分类
})
const page = reactive({
  // kaiDate:'',
  // endDate:'',
  basicInforId: '',
  bedroomId: '',
  turnBuilding: '',
  nestNumber: '',
  pageIndex: 1,
  pageSize: 3,
  totalCount: 0,
  pageCount: 0
})

//母猪分娩列表
const tableData = ref([])
const loadData = () => {
  axios.post(apiBedinUrl+'/api/Farrowings/ShowFarrowings', {
    // kaiDate:page.kaiDate,
    // endDate:page.endDate,
    basicInforId: page.basicInforId || 0,
    bedroomId: page.bedroomId || 0,
    turnBuilding: page.turnBuilding,
    nestNumber: page.nestNumber,
    pageIndex: page.pageIndex,
    pageSize: page.pageSize
  })
    .then(res => {
      console.log("母猪分娩列表", res.data.data.list);
      tableData.value = res.data.data.list;
      page.totalCount = res.data.data.totalCount;
      page.pageCount = res.data.data.pageCount;
    })
}

//猪只信息耳号列表
const BasicInformationList = ref([]);
const GetBasicInformation = () => {
  axios.post(apiBedinUrl+'/api/Infancies/GetBasicInformation', {})
    .then(res => {
      console.log("猪只信息耳号", res.data.data);
      BasicInformationList.value = res.data.data;
    })
}

//删除
const Del = (farrowingId: number) => {
  ElMessageBox.confirm(
    '确认要删除吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.put(apiBedinUrl+'/api/Farrowings/DeleteFarrowings', {
        farrowingId: farrowingId
      })
        .then(res => {
          if (res.data.code == 0) {
            ElMessage.success('删除成功');
            loadData();
          }
          else {
            ElMessage.error('删除失败');
            return;
          }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

//查看母猪分娩详情修改
const Getfarrowing = (farrowingId: number) => {
  router.push({
    path: '/UpdateFarrorings',
    query: {
      farrowingId: farrowingId
    }
  })
}

//响应式数据 获取栋舍
const condition=reactive({
    pageIndex:1,
    pageSize:100,
    bedroomTypeId:0,
    bedroomName:'',
    personName:''
})
//获取栋舍
const bedroomList:any=ref([])
const handleBedroom=()=>{
    axios.post(apiUrl+'/api/BedRoom/ShowBedroom',{
        pageIndex: condition.pageIndex,
        pageSize: condition.pageSize,
        bedroomTypeId: condition.bedroomTypeId,
        bedroomName: condition.bedroomName,
        personName:condition.personName
    }).then(res=>{
        console.log("栋舍",res.data.data)
        bedroomList.value=res.data.data.list
    })
}

//导出
const Export = () => {
  location.href = apiBedinUrl+'/api/Farrowings/ExportFarrowingsExcel' + '';
  // window.open(
  //     apiBedinUrl+'/api/Farrowings/ExportFarrowingsExcel',
  //     '_self'
  //   );
}

// 定义一个响应式变量excelFile，用于存储选中的Excel文件
const excelFile=ref({})
//获取文件
const handleFileUpload=(event:any)=>{
  // 打印选中的文件（第一个文件，因为可能允许选择多个文件）
  console.log(event.target.files[0])

  // 将事件的目标元素（通常是<input type="file">）强制转换为HTMLAnchorElement类型，但这里应该是HTMLInputElement
  // 注意：这里应该是HTMLInputElement，因为处理文件上传通常是通过<input type="file">元素
  const input=event.target as HTMLAnchorElement;// 更正类型
  // 如果选择了文件
  if(input.files.length>0){
    // 将选中的文件赋值给excelFile.value
    excelFile.value=input.files[0]
  }

}
//导入
const ImportFarrow=()=>{
  if(!excelFile.value){
    ElMessage.error("请选择要导入的文件!!");
    return;
  }
  else{
    // 创建一个FormData对象，用于构建一组键值对，表示表单字段和其值，以便使用XMLHttpRequest发送数据
    const formData = new FormData();
    // 将选中的文件添加到formData对象中，键名为'file'
    formData.append('file',excelFile.value);

    axios.post(apiBedinUrl+'/api/Farrowings/ImportFarrowings',formData)
   .then(res=>{
    if (res.data.code == 0) {
        console.log("母猪分娩导入", res.data);
        ElMessage.success('母猪分娩导入成功');
        //刷新
        loadData()
    }else {
      ElMessage.error('母猪分娩导入失败');
    }
   })
  }
}

//分页
const handleSizeChange = (val: number) => {
  page.pageSize = val;
  loadData();
};
const handleCurrentChange = (val: number) => {
  page.pageIndex = val;
  loadData();
};
</script>
